<template>
  <basic-dialog
    :visible="visible"
    min-width="760px"
    :is-show-basic-footer="!loadingPage"
    @close="handleClose"
    @submit="handleOk"
    :loading="submitting"
    title="新建网关">
    <div class="gateway-container" v-if="loadingPage">
      <Loading/>
    </div>
    <div class="gateway-container" v-else>
      <div class="left">
        <transition
          appear
          enter-active-class="animated bounceInDown"
          leave-active-class="animated fadeOut"

        >
          <img id="gateway" :src="require('../../../../statics/img/gateway.png')" alt="gateway">
        </transition>
      </div>
      <div class="right">
        <q-form ref="form">
          <yz-input
            v-model.trim="formData.gateWayId"
            :rules="[0]"
            :hint-rule="[val => val && val.length > 0  || '请填写网关序列号',
                    val => val && /^[0-9a-zA-Z]*$/g.test(val) || '只能输入数字或者字母']"
            title="网关序列号"
          />

          <yz-input
            v-model="formData.productModel"
            inputType="select"
            class="margin-r-30"
            :rules="[0]"
            :options="productModelOptions"
            title="产品型号"
          ></yz-input>
        </q-form>
      </div>
    </div>

  </basic-dialog>
</template>

<script>

import { checkBoxNew, createBox, getBoxProducts } from '../../../../boot/miot/list'
import { createLatestBox } from '../../../../boot/miot/plc-list'
import { Dialog } from 'quasar'
import Loading from './gateway-dialog/loading.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'new-gateway-all-type',
  components: {
    Loading
  },
  props: {
    products: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      submitting: false,
      visible: false,
      showFooter: true,
      isNewCnc: true,
      initLoading: false,
      formData: {
        gateWayId: '',
        productModel: '',
        productId: ''
      }
    }
  },
  computed: {
    ...mapGetters(['client']),
    productModelOptions () {
      const data = []
      this.products.forEach(item => {
        data.push({
          value: item.productSN,
          label: item.productName
        })
      })
      return data
    },
    loadingPage () {
      return !this.isNewCnc && this.initLoading
    }
  },
  methods: {
    showDialog () {
      this.visible = true
      Object.assign(this.formData, this.$options.data().formData)
    },
    // 提交请求
    handleOk () {
      this.$refs['form'].validate(true).then(async res => {
        if (res) {
          this.submitting = true
          const productItem = this.productModelOptions.find(item => item.value === this.formData.productModel)
          const productName = productItem.label
          // 检查是否是新盒子
          const rs = await checkBoxNew(this.formData.gateWayId, this.formData.productModel)
          const isNew = rs.data
          this.isNewCnc = isNew
          // 如果是新的盒子
          if (isNew) {
            try {
              const index = this.products.findIndex(item => item.productSN === this.formData.productModel)
              const { data } = await createLatestBox(this.formData.gateWayId, this.products[index].productSN, this.products[index].productName)
              this.$router.push({
                name: 'plcDetail',
                query: {
                  boxRemark: data.boxRemark,
                  boxId: data.ucloudBoxNum,
                  productId: this.products[index].productSN,
                  boxNum: data.boxNum,
                  updateVersion: 2,
                  _time: new Date().getTime()
                }
              })
              this.handleClose()
              this.$emit('success')
            } catch (e) {
              this.$message.error('初始化网关失败')
            } finally {
              this.submitting = false
            }
          } else {
            // 获取老盒子序列号
            try {
              const oldProduct = await getBoxProducts()
              const productItemOld = oldProduct.data?.products.find(item => item.name === productName)
              this.formData.productId = productItemOld.product_id
              // const boxId = this.formData.productId + '_' + this.formData.gateWayId
              const rs = await createBox(this.formData.gateWayId, this.formData.productId, productName)
              if (!rs.success) {
                this.$message.error('初始化网关失败')
                return
              }
              try {
                this.initLoading = true
                // 检查盒子是否在线
                await this.checkOnline()
                this.$emit('success', this.formData.gateWayId)
              } catch (e) {
                this.handleClose()
              }
            } catch (e) {
              this.$message.error('初始化网关失败')
            } finally {
              this.submitting = false
            }
          }
        }
      })
    },
    // 关闭页面
    handleClose () {
      this.initLoading = false
      this.visible = false
    },
    /**
     * 检查盒子是否在线
     */
    checkOnline () {
      return new Promise((resolve, reject) => {
        if (this.client && this.client.connected) {
          const boxId = this.formData.productId + '_' + this.formData.gateWayId
          const subscribe = this.client.subscribe(
            `/topic/create/newBox/${boxId}`,
            (message) => {
              try {
                subscribe.unsubscribe()
                const ret = JSON.parse(message.body)
                if (ret && ret.data && ret.data.status === 'ONLINE') {
                  resolve()
                } else {
                  Dialog.create({
                    title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>设备未在线，请检查设备网络</p>`,
                    html: true,
                    ok: {
                      unelevated: true,
                      label: '确认'
                    }
                  })
                  reject()
                }
              } catch (e) {
                console.log('解析socket内存报警错误' + e)
                reject()
              }
            }
          )
        } else {
          Dialog.create({
            title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>websocket断开连接啦~请稍后重试</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          reject()
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
/deep/.label-width{
  width: 100px;
}
/deep/.q-field__bottom{
  padding-top: 4px;
}
.gateway-container{
  height: 515px;
  display: flex;

  .left,
  .right{
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
#gateway{
  animation-duration: 1s;
}
</style>
